package com.sdhillon.gallery;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.sdhillon.R;

public class GridThumbnailView extends Activity implements OnItemClickListener {
	private static final String TAG = GridThumbnailView.class.getSimpleName();
	private static final String KEY_THUMB_URLS = "thumbUrls";
	private static final String KEY_MEDIUM_URLS = "medUrls";
	private static final String KEY_TITLES = "titles";
	private static final String KEY_PAGE = "page";
	private static final String KEY_TOTAL_PAGES = "totalPages";

	private static final String GROUP_ID = "1308171@N25"; // an android group

	private ArrayList<String> mThumbnailUrls;
	private ArrayList<String> mMediumUrls;
	private ArrayList<String> mTitles;
	private int mPage;
	private int mTotalPages = 1;
	private GridThumbnailAdapter mThumbAdapter;
	private GridView mThumbGrid;

	/** Called when the activity is first created. */
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grid_thumb_view);

		mThumbGrid = (GridView) findViewById(R.id.gridview);
		if (savedInstanceState != null) {
			mThumbnailUrls = (ArrayList<String>) savedInstanceState
					.getSerializable(KEY_THUMB_URLS);
			mMediumUrls = (ArrayList<String>) savedInstanceState
					.getSerializable(KEY_MEDIUM_URLS);
			mTitles = (ArrayList<String>) savedInstanceState
					.getSerializable(KEY_TITLES);
			mPage = savedInstanceState.getInt(KEY_PAGE);
			mTotalPages = savedInstanceState.getInt(KEY_TOTAL_PAGES);

			mThumbAdapter = new GridThumbnailAdapter(this, mThumbnailUrls,
					android.R.drawable.ic_menu_gallery);
		} else {
			mThumbnailUrls = new ArrayList<String>();
			mMediumUrls = new ArrayList<String>();
			mTitles = new ArrayList<String>();
			mPage = 1;

			mThumbAdapter = new GridThumbnailAdapter(this, mThumbnailUrls,
					android.R.drawable.ic_menu_gallery);
			new DownloadImages().execute(mPage);
		}
		mThumbGrid.setAdapter(mThumbAdapter);

		mThumbGrid.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position,
			long id) {
		Toast.makeText(this, mTitles.get(position), Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(TAG, "saving state");
		outState.putSerializable(KEY_THUMB_URLS, mThumbnailUrls);
		outState.putSerializable(KEY_MEDIUM_URLS, mMediumUrls);
		outState.putSerializable(KEY_TITLES, mTitles);
		outState.putInt(KEY_PAGE, mPage);
		outState.putInt(KEY_TOTAL_PAGES, mTotalPages);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		ProgressDialog dialog = new ProgressDialog(this);
		dialog.setMessage("Loading images");
		dialog.setIndeterminate(true);
		return dialog;
	}

	/* Creates the menu items */
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.gallery_menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// disable the menu if we don't have any more pages
		menu.findItem(R.id.load).setEnabled(mPage < mTotalPages);
		return super.onPrepareOptionsMenu(menu);
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.load:
			// load next page
			new DownloadImages().execute(++mPage);
			return true;
		}
		return false;
	}

	private class DownloadImages extends
			AsyncTask<Integer, Void, FlickrHelper.FlickrResult> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// only show the loading dialog on the first page
			if (mPage == 1) {
				showDialog(0);
			}
		}

		@Override
		protected FlickrHelper.FlickrResult doInBackground(Integer... params) {
			FlickrHelper.FlickrResult res = null;
			try {
				res = FlickrHelper.getGroupPhotos(GROUP_ID, params[0]);
			} catch (IOException e) {
				e.printStackTrace();
				cancel(false);
			}
			return res;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			finish();
			Toast.makeText(GridThumbnailView.this,
					"Error loading Gallery. Please try again later.",
					Toast.LENGTH_LONG).show();
		}

		protected void onPostExecute(FlickrHelper.FlickrResult result) {
			if (isCancelled() || result == null) {
				finish();
				Toast.makeText(GridThumbnailView.this,
						"Error loading Gallery. Please try again later.",
						Toast.LENGTH_LONG).show();
				return;
			}
			mThumbnailUrls.addAll(result.thumbnailUrls);
			mMediumUrls.addAll(result.mediumUrls);
			mTitles.addAll(result.titles);
			mTotalPages = result.totalPages;

			mThumbAdapter.notifyDataSetChanged();

			if (mPage == 1) {
				dismissDialog(0);
			}
		}
	}

	public static void showView(Context c) {
		c.startActivity(new Intent(c, GridThumbnailView.class));
	}
}